package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.SQLPageDoing;
import com.rockcent.mall.lib.domain.enumclass.MarketMerchantCooperationStatus;
import com.rockcent.mall.lib.domain.enumclass.MerchantCooperationType;
import com.rockcent.mall.lib.dto.MarketMerchantCooperationRecordDto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * Created by oyhk on 14-6-22.
 *
 */
@Repository
public class MarketMerchantCooperationRecordRepositoryImpl implements MarketMerchantCooperationRecordRepositoryCustom {

    private static final Logger log = LoggerFactory.getLogger(MarketMerchantCooperationRecordRepositoryImpl.class);

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public PageResult findPage(Long merchantId, String merchantName, MarketMerchantCooperationStatus status, MerchantCooperationType type, PageResult pageResult) {
        SQLPageDoing doing = (sql, fields, params, typeReferenceMap) -> {
            sql.append("select %s from market_merchant_cooperation_record mcr where 1 = 1 ");
            // 分销商 分页记录
            if (type == MerchantCooperationType.DISTRIBUTOR) {
                sql.append(" and mcr.supplier_merchant_id = :merchantId");
                params.put("merchantId",merchantId);

                if(!StringUtils.isBlank(merchantName)){
                    sql.append(" and mcr.distributor_merchant_name like :merchantName");
                    params.put("merchantName","%"+merchantName+"%");
                }
            } else if (type == MerchantCooperationType.SUPPLIER) {
                sql.append(" and mcr.distributor_merchant_id = :merchantId");
                params.put("merchantId",merchantId);

                if(!StringUtils.isBlank(merchantName)){
                    sql.append(" and mcr.supplier_merchant_name like :merchantName");
                    params.put("merchantName","%"+merchantName+"%");
                }
            }

            if(status != null && status != MarketMerchantCooperationStatus.ALL) {
                sql.append(" and mcr.status = :status");
                params.put("status", status.toString());
            }

            sql.append(" order by mcr.date_created desc");
            fields.append("mcr.*");
        };
        return doing.go(pageResult, MarketMerchantCooperationRecordDto.class, objectMapper, jdbcTemplate, log);
    }
}
